package com.study.test.controller;

import org.springframework.beans.factory.annotation.Value;


import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController

public class FileDownloadController {
    @Value("${download-dir}")
    private String filePath;
    @GetMapping("/download/{filename}")
    public void download(@PathVariable  String filename, HttpServletResponse response){

        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(filePath + filename));

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            response.setHeader("content-disposition","attachment;filename=");//以附件的形式
//            response.setContentType("image/jpeg");//以图片的形式

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
